import { Component, OnInit } from '@angular/core';
import {MapUtil} from "../../../util/map-util";

declare var echarts;
declare var $;
declare var BMap;
declare var BMapLib;

@Component({
  selector: 'app-big-screen-airquality',
  templateUrl: './big-screen-airquality.component.html',
  styleUrls: ['./big-screen-airquality.component.css']
})
export class BigScreenAirqualityComponent implements OnInit {

  blist: Array<any> = [];
  districtLoading:any = 0;
  map: any;

  constructor(
    private mapUtil : MapUtil,
  ) { }

  ngOnInit() {
    this.mapUtil.loadMapScript( ()=> this.init());
    this.mapUtil.loadMapLib('http://api.map.baidu.com/library/AreaRestriction/1.2/src/AreaRestriction_min.js');
    this.showChart();
  }
  /**
   * 初始化地图
   */
  initMap () {
    $("#map").css("height",window.innerHeight-195+"px");
    this.map = new BMap.Map("dvAirMap",{enableMapClick:false,minZoom:5,maxZoom:18});
    let centerPoint = new BMap.Point(113.658221,34.780377);  // 创建点坐标
    this.map.centerAndZoom(centerPoint, 12);
    //地图样式
    let mapStyle = [
      {
        "featureType": "poi",
        "elementType": "all",
        "stylers": {
          "visibility": "off"
        }
      },
      {"featureType" : "land",
        "elementType": "geometry",
        "stylers": {
          "color": "#24252b"
        }
      },
      {"featureType": "road",
        "elementType": "geometry",
        "stylers": {
          "color": "#171717",
          "hue": "#171717",
          "weight": "0.1",
          "lightness": -6,
          "saturation": -15
        }
      },
      {
        "featureType": "highway",
        "elementType": "labels.icon",
        "stylers": {
          "visibility": "off"
        }
      },
      {"featureType": "building",
        "elementType": "geometry",
        "stylers": {
          "color": "#2a2b2e"
        }
      },
      {"featureType": "highway",
        "elementType": "all",
        "stylers": {
          "lightness": -42,
          "saturation": -91
        }
      },
      {"featureType": "arterial",
        "elementType": "geometry",
        "stylers": {
          "lightness": -77,
          "saturation": -94
        }
      },
      {"featureType": "green",
        "elementType": "geometry",
        "stylers": {
          "color": "#1b1b1b"
        }
      },
      {"featureType": "subway",
        "elementType": "geometry.stroke",
        "stylers": {
          "color": "#181818"
        }
      },
      {"featureType": "railway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -52
        }
      },
      {"featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": {
          "color": "#313131"
        }
      },
      {"featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": {
          "color": "#8b8787"
        }
      },
      {"featureType": "manmade",
        "elementType": "geometry",
        "stylers": {
          "color": "#1b1b1b"
        }
      },
      {"featureType": "local",
        "elementType": "geometry",
        "stylers": {
          "lightness": -75,
          "saturation": -91
        }
      },
      {"featureType": "subway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -65
        }
      },
      {"featureType": "railway",
        "elementType": "all",
        "stylers": {
          "lightness": -40
        }
      },
      {"featureType": "road",
        "elementType": "geometry",
        "stylers": {
          "color": "#171717",
          "hue": "#041e3b",
          "weight": "1.0",
          "lightness": -12,
          "saturation": -15
        }
      },
      {"featureType": "water",
        "elementType": "geometry",
        "stylers": {
          "color": "#041e3b",
          "hue": "#041e3b",
          "weight": "0.1",
          "lightness": -12,
          "saturation": -15
        }
      }
    ];
    this.map.setMapStyle({styleJson:mapStyle});
    this.map.enableScrollWheelZoom();
    this.map.enableDragging();
  }

  init () {
    this.map = new BMap.Map("dvAirMap", { enableMapClick: false,minZoom:10,maxZoom:11 }); // 创建地图实例，禁止点击地图底图
    let mapStyle = [
      {
        "featureType": "poi",
        "elementType": "all",
        "stylers": {
          "visibility": "on"
        }
      },
      {
        "featureType": "land",
        "elementType": "geometry",
        "stylers": {
          "color": "#24252b"
        }
      },
      {
        "featureType": "road",
        "elementType": "geometry",
        "stylers": {
          "color": "#171717",
          "hue": "#171717",
          "weight": "0.1",
          "lightness": -6,
          "saturation": -15
        }
      },
      {
        "featureType": "highway",
        "elementType": "labels.icon",
        "stylers": {
          "visibility": "off"
        }
      },
      {
        "featureType": "building",
        "elementType": "geometry",
        "stylers": {
          "color": "#2a2b2e"
        }
      },
      {
        "featureType": "highway",
        "elementType": "all",
        "stylers": {
          "lightness": -42,
          "saturation": -91
        }
      },
      {
        "featureType": "arterial",
        "elementType": "geometry",
        "stylers": {
          "lightness": -77,
          "saturation": -94
        }
      },
      {
        "featureType": "green",
        "elementType": "geometry",
        "stylers": {
          "color": "#1b1b1b"
        }
      },
      {
        "featureType": "subway",
        "elementType": "geometry.stroke",
        "stylers": {
          "color": "#181818"
        }
      },
      {
        "featureType": "railway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -52
        }
      },
      {
        "featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": {
          "color": "#313131"
        }
      },
      {
        "featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": {
          "color": "#8b8787"
        }
      },
      {
        "featureType": "manmade",
        "elementType": "geometry",
        "stylers": {
          "color": "#1b1b1b"
        }
      },
      {
        "featureType": "local",
        "elementType": "geometry",
        "stylers": {
          "lightness": -75,
          "saturation": -91
        }
      },
      {
        "featureType": "subway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -65
        }
      },
      {
        "featureType": "railway",
        "elementType": "all",
        "stylers": {
          "lightness": -40
        }
      },
      {
        "featureType": "road",
        "elementType": "geometry",
        "stylers": {
          "color": "#171717",
          "hue": "#041e3b",
          "weight": "1.0",
          "lightness": -12,
          "saturation": -15
        }
      },
      {
        "featureType": "water",
        "elementType": "geometry",
        "stylers": {
          "color": "#041e3b",
          "hue": "#041e3b",
          "weight": "0.1",
          "lightness": -12,
          "saturation": -15
        }
      }
    ];
    this.map.setMapStyle({
      styleJson: mapStyle
    });

    // this.map.disableDragging();//禁止拖动
    this.map.enableScrollWheelZoom(true);
    this.map.disableDoubleClickZoom();//禁止双击缩放


    setTimeout( () => {
      this.getBoundary();
    }, 100);
  }

  getBoundary() {
    this.addDistrict("郑州");
  }
  /**
   * 添加行政区划
   * @param {} districtName 行政区划名
   * @returns  无返回值
   */
  addDistrict(districtName) {
    //使用计数器来控制加载过程
    this.districtLoading++;
    let bdary = new BMap.Boundary();
    bdary.get(districtName,  (rs) => {       //获取行政区域
      let count = rs.boundaries.length; //行政区域的点有多少个
      if (count === 0) {
        alert('未能获取当前输入行政区域');
        return;
      }
      for (let i = 0; i < count; i++) {
        this.blist.push({ points: rs.boundaries[i], name: districtName });
      };
      //加载完成区域点后计数器-1
      this.districtLoading--;
      if (this.districtLoading == 0) {
        //全加载完成后画端点
        this.drawBoundary();
      }
    });
  }
  drawBoundary() {
    //包含所有区域的点数组
    let pointArray = [];

    /*画遮蔽层的相关方法
     *思路: 首先在中国地图最外画一圈，圈住理论上所有的中国领土，然后再将每个闭合区域合并进来，并全部连到西北角。
     *      这样就做出了一个经过多次西北角的闭合多边形*/
    //定义中国东南西北端点，作为第一层
    let pNW = { lat: 59.0, lng: 73.0 }
    let pNE = { lat: 59.0, lng: 136.0 }
    let pSE = { lat: 3.0, lng: 136.0 }
    let pSW = { lat: 3.0, lng: 73.0 }
    //向数组中添加一次闭合多边形，并将西北角再加一次作为之后画闭合区域的起点
    let pArray = [];
    pArray.push(pNW);
    pArray.push(pSW);
    pArray.push(pSE);
    pArray.push(pNE);
    pArray.push(pNW);
    //循环添加各闭合区域
    for (let i = 0; i < this.blist.length; i++) {
      //添加多边形层并显示
      let ply = new BMap.Polygon(this.blist[i].points, { strokeWeight: 5, strokeColor: "#2A5BDC", fillOpacity: 0.01, fillColor: " transparent" }); //建立多边形覆盖物
      ply.name = this.blist[i].name;
      this.map.addOverlay(ply);

      //将点增加到视野范围内
      let path = ply.getPath();
      pointArray = pointArray.concat(path);
      //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
      pArray = pArray.concat(path);
      pArray.push(pArray[0]);
    }

    //限定显示区域，需要引用api库
    let boundply = new BMap.Polygon(pointArray);
    // console.log(boundply.getBounds());
    let bound = new BMap.Bounds( new BMap.Point(pSE.lng,pSE.lat) ,  new BMap.Point(pSW.lng,pSW.lat));
    // console.log(bound);
    BMapLib.AreaRestriction.setBounds(this.map, boundply.getBounds());
    // BMapLib.AreaRestriction.setBounds(this.map, bound);
    this.map.setViewport(pointArray);    //调整视野

    //添加遮蔽层
    let plyall = new BMap.Polygon(pArray, { strokeOpacity: 0.0000001, strokeColor: "#000000", strokeWeight: 0.00001, fillColor: "#070E27", fillOpacity: 1 }); //建立多边形覆盖物
    this.map.addOverlay(plyall);
  }

  /**
   * 显示图表
   */
  showChart(){
    // 站点分类
    let siteChart = echarts.init(document.getElementById('siteCategory'));
    let siteOption = {
      title: {
        text: ['{title1|47}{sub|个}','{title2| 在线监测站点 }'].join('\n'),
        x: '17%',
        y: 'center',
        textStyle: {
          color: '#dbc4ad',
          fontSize: 26,
          rich: {
            title1: {
              fontSize: 24,
              color: '#fff',
              align:'center'
            },
            title2: {
              fontSize: 14,
              color: '#fff',
            },
            sub:{
              fontSize: 14,
              color: '#fff',
              // padding: [10]
            }
          }
        }
      },
      legend: {
        orient: 'vertical',
        top: 'center',
        right: 30,
        selectedMode:false,
        data: [
          {
            name:'国控站',
            icon:'circle'
          },
          {
            name:'小型站',
            icon:'circle'
          }
        ],
        textStyle: {
          color: '#fff'
        }
      },
      color:['#5A84E5','#195AEE'],
      tooltip : {
        // trigger: 'item',
        // formatter: "{a} <br/>{b} : {c} ({d}%)"
        show: false
      },
      grid : {
        top: 'middle',
        left: '10%',
        right: '10%'
      },
      series : [
        {
          name: '访问来源',
          type: 'pie',
          center:['30%','50%'],
          radius : ['50%', '60%'],
          hoverOffset:0,
          data:[
            {value:335, name:'小型站'},
            {value:310, name:'国控站'},
          ],
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          labelLine: {
            normal: {
              show: false
            }
          },
          label: {
            normal: {
              show: false,
            }
          },
        },
        {
          type: 'pie',
          center:['30%','50%'],
          radius: ['0%','50%'],
          hoverAnimation: false,
          label: {
            normal: {
              show: false,
            }
          },
          data:[
            {
              value: 100,
              itemStyle: {
                normal: {
                  color: '#262932'
                }
              }
            },{
              value:0
            }
          ]
        }
      ]
    };
    siteChart.setOption(siteOption);

    // 空气优良天数情况
    let airChart = echarts.init(document.getElementById('airQuality'));
    let airOption = {
      title: {
        text: ['{title1|100}','{sub|/200}','{title2| 优良天数 }'].join('\n'),
        x: '20%',
        y: 'center',
        textStyle: {
          color: '#dbc4ad',
          fontSize: 26,
          rich: {
            title1: {
              fontSize: 24,
              color: '#fff',
              align:'center'
            },
            title2: {
              fontSize: 14,
              color: '#fff',
            },
            sub:{
              fontSize: 14,
              color: '#fff',
              align:'center'
            }
          }
        }
      },
      color:['#5A84E5','#195AEE'],
      legend: {
        orient: 'vertical',
        top: 'center',
        right: 30,
        selectedMode:false,
        data: [
          {
            name:'目标值',
            icon:'circle'
          },
          {
            name:'实际值',
            icon:'circle'
          }
        ],
        textStyle: {
          color: '#fff'
        }
      },
      tooltip : {
        show: false
      },
      grid : {
        top: 'middle',
        left: '10%',
        right: '10%'
      },
      series : [
        {
          center: ["30%", "50%"],
          radius: ["49%", "50%"],
          clockWise: false,
          hoverAnimation: false,
          type: "pie",
          itemStyle:{
            emphasis:{
              label: {
                show: false
              },
              labelLine: {
                show: false
              }
            }
          },
          data: [
            {
              name:'实际值'  ,
              value: 40,
              itemStyle: {
                normal: {
                  label: {
                    show: false
                  },
                  labelLine: {
                    show: false
                  },
                  // color: "#5A84E5",
                  borderColor: "#5A84E5",
                  borderWidth: 10
                }
              }
            },
            {
              name: "目标值",
              value: 40,
              itemStyle: {
                normal: {
                  label: {
                    show: false
                  },
                  labelLine: {
                    show: false
                  },
                  color: "#195AEE",
                  borderColor: "#195AEE",
                  borderWidth: 1
                }
              }
            },
            {
              value: 25,
              name: 'invisible',
              itemStyle: {
                normal : {
                  color: 'rgba(0,0,0,0)',
                  label: {show:false},
                  labelLine: {show:false},
                  borderWidth: 0,
                  borderColor: "transparent",
                }
              }
            },
          ]
        },
        {
          type: 'pie',
          center:['30%','50%'],
          radius: ['60%','64%'],
          hoverAnimation: false,
          label: {
            normal: {
              show: false,
            }
          },
          data:[
            {
              value: 100,
              itemStyle: {
                normal: {
                  color: '#171C33'
                }
              }
            },{
              value:0
            }
          ]
        }
      ]
    };
    airChart.setOption(airOption);

    // 站点联网状态
    let lineChart = echarts.init(document.getElementById('siteLine'));
    let lineOption = {
      title: {
        text: ['{title1|47}{sub|个}','{title2| 站点联网 }'].join('\n'),
        x: '20%',
        y: 'center',
        textStyle: {
          color: '#dbc4ad',
          fontSize: 26,
          rich: {
            title1: {
              fontSize: 24,
              color: '#fff',
              align:'center'
            },
            title2: {
              fontSize: 14,
              color: '#fff',
            },
            sub:{
              fontSize: 14,
              color: '#fff',
              // padding: [10]
            }
          }
        }
      },
      legend: {
        orient: 'vertical',
        top: 'center',
        right: 30,
        selectedMode:false,
        data: [
          {
            name:'在线',
            icon:'circle'
          },
          {
            name:'异常',
            icon:'circle'
          },
          {
            name:'离线',
            icon:'circle'
          }
        ],
        textStyle: {
          color: '#fff'
        }
      },
      color:['#5A84E5','#195AEE','#495D8A'],
      tooltip : {
        // trigger: 'item',
        // formatter: "{a} <br/>{b} : {c} ({d}%)"
        show: false
      },
      grid : {
        top: 'middle',
        left: '10%',
        right: '10%'
      },
      series : [
        {
          name: '访问来源',
          type: 'pie',
          center:['30%','50%'],
          radius : ['50%', '60%'],
          hoverOffset:0,
          data:[
            {value:335, name:'在线'},
            {value:310, name:'异常'},
            {value:150, name:'离线'},
          ],
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          labelLine: {
            normal: {
              show: false
            }
          },
          label: {
            normal: {
              show: false,
            }
          },
        },
        {
          type: 'pie',
          center:['30%','50%'],
          radius: ['0%','50%'],
          hoverAnimation: false,
          label: {
            normal: {
              show: false,
            }
          },
          data:[
            {
              value: 100,
              itemStyle: {
                normal: {
                  color: '#262932'
                }
              }
            },{
              value:0
            }
          ]
        }
      ]
    };
    lineChart.setOption(lineOption);

    // 当日累计AQI趋势图
    let AQIChart = echarts.init(document.getElementById('AQICount'));
    let dataList =  [
      [ "88", "86", "85", "82", "81", "78", "77", "76", "73", "71", "67", "66", "65", "66", "67", "-", "-", "-", "-", "-", "-", "-", "-", "-" ], [ "122", "97", "65", "153", "153", "70", "135", "106", "148", "112", "122", "110", "95", "159", "76", "137", "143", "154", "114", "121", "120", "155", "67", "145" ],
      [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "0" ] ];
    let dayCountAQI  = {
      tooltip : {
        trigger: 'axis',
        formatter:function(params,ticket,callback){
          params[1].value = params[1].value?params[1].value:"-";
          params[0].value = params[0].value?params[0].value:"-";
          return params[0].name+"时 </br>"+params[0].seriesName+":"+params[0].value;
          /*+" </br>"+params[1].seriesName+":"+params[1].value*/ /*预计AQI悬停数据*/
        }
      },
      legend: {
        data:[],
        selectedMode:false,
        right: 10,
        y:'center',
        orient:'vertical',
        textStyle:{
          color:'#fff'
        }
      },
      grid: {
        // left: '30',
        right: '120',
        // top: '25',
        // bottom:"25"
      },
      xAxis : [
        {
          type : 'category',
          boundaryGap : false,
          data : dataList[2],
          axisLine:{
            lineStyle:{
              color:'#fff'
            }
          },
          axisLabel:{
            color:'#fff'
          }
        }
      ],
      yAxis : [
        {
          type : 'value',
          axisLine:{
            lineStyle:{
              color:'#fff'
            }
          },
          axisLabel:{
            color:'#fff'
          }
        },
      ],
      series : [
        {
          name:'当前AQI',
          type:'line',
          lineStyle:{
            normal:{
              width:0,
              type:"dashed",
              color:"#aaa4a4"
            }
          },
          symbol: 'none',
          zlevel:2,
          areaStyle: {
            normal: {
              // color: color
            }
          },
          data:dataList[0]
        }
      ]
    };
    let realData = [];
    $.each(dataList[0],function(i,real){
      if(real!="-"){
        realData.push(real);
      }
    });
    let realMaxNum = Math.max.apply(Math, realData);
    let predictMaxNum = Math.max.apply(Math, dataList[1]);
    let maxNum =  realMaxNum>predictMaxNum?realMaxNum:predictMaxNum;
    let fineLine: any = {
      name:'良',
      type:'line',
      itemStyle:{
        normal:{
          color:"#CCB21A"
        }
      },
      symbol: 'none',
      data:[100, 100, 100, 100, 100, 100, 100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100]
    };
    let lightLine: any =  {
      name:'轻度污染',
      type:'line',
      itemStyle:{
        normal:{
          color:"#F5A623"
        }
      },
      symbol: 'none',
      data:[150, 150, 150, 150, 150, 150, 150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150]
    };
    let mediumLine: any = {
      name:'中度污染',
      type:'line',
      itemStyle:{
        normal:{
          color:"#FF331E"
        }
      },
      symbol: 'none',
      data:[200, 200, 200, 200, 200, 200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200]
    };
    (maxNum>50) && dayCountAQI.series.push(fineLine) && dayCountAQI.legend.data.push("良");
    (maxNum>100) && dayCountAQI.series.push(lightLine) && dayCountAQI.legend.data.push("轻度污染");
    (maxNum>150) && dayCountAQI.series.push(mediumLine) && dayCountAQI.legend.data.push("中度污染");
    AQIChart.setOption(dayCountAQI);

}
}
